var gDisplayedReadableItem = "";
var alertIcon = "<span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin:0 7px 20px 0;\"></span>";

jQuery(window).load(function()
{
	jQuery("button").button();
	hideLoading();
	jQuery("#alertDialog").hide();
	jQuery("#searchInput").focus();
});  

function showLoading() 
{
    jQuery("#loading").show();
}

function hideLoading()     
{
    jQuery("#loading").hide();
}  

$(function () 
{    	
    $("#menu").jstree({       	
        "xml_data" : 
        {
            "data" : gMenu
        },
        "ui" : 
        {
            "select_limit" : 1
        },            
        "types" : 
        {
            "types" : 
            {
                "default" : 
                { 
                	"icon" : { "image" : "images/folder.png" }  
                },              	
                "file" : 
                {
                    "valid_children" : [ "none" ],
                    "icon" : { "image" : "images/readable.png" }                      
                }                   
            }
        },
        /*"sort" : 
        function (a, b) 
        { 
        	if ((this._get_node(a).attr("rel") == "undefined") && (this._get_node(b).attr("rel") == "undefined"))
        	{
        		return this.get_text(a) > this.get_text(b) ? 1 : -1; 
        	}
        	else if ((this._get_node(a).attr("rel") == "undefined") && (this._get_node(b).attr("rel") == "file"))
        	{
        		return -1;
        	}
        	else if ((this._get_node(a).attr("rel") == "file") && (this._get_node(b).attr("rel") == "undefined"))
        	{
        		return 1;
        	}      
        	else
        	{
        		return this.get_text(a) > this.get_text(b) ? 1 : -1;
        	}            
        },*/
        "plugins" : [ "themes", "xml_data", "checkbox", "ui", "types" ]
    });
    
    // When tree is loaded
    $("#menu").bind("loaded.jstree", function (event, data) 
    {
        //$('#menu').jstree('check_node', 'ul > li:first');
        // Tick the first checkbox
        data.inst.check_node("ul > li:first");
    });
    
    // When a node is selected
    $("#menu").bind("select_node.jstree", function(event, data)
    {   
    	var type = data.rslt.obj.attr("rel");

    	if (type == "file") // what to do when it is a file
    	{        		
    		var nodeId = data.rslt.obj.attr("id");
    		
    		showContents(nodeId, null, null);
    	}
    	else if ((type == null) || (type == "undefined")) // What to do when it is not a file (i.e. a folder)
    	{
    		// data.inst is the tree object, and data.rslt.obj is the node
    		return data.inst.toggle_node(data.rslt.obj);
    	}
    });    
    
    jQuery("#menuAccordion").height(gHeightOfMiddleSection).css({overflow:"auto", width:"100%"});
    //jQuery("#menu").height(gHeightOfMiddleSection - 150).css({overflow:"auto", width:"100%"});
    
    // Ensure the width of the menu section is kept
    jQuery("#menuAccordion").width(gWidthOfMenu);
        
    // Menu accordion
    jQuery("#menuAccordion").accordion(
    { 
    	header: "h3", 
    	clearStyle: true, 
    	autoHeight: false,
    	change: function(event, ui) 
    	{
    		$('#menu').jstree("get_selected").each(function () 
    		{                   
                if (this.id != gDisplayedReadableItem)
                {
                    $('#menu').jstree("deselect_all");
                }
            });
    		
            $('#searchResultsMenu').jstree("get_selected").each(function () 
            {                    
            	var parent = $(this).jstree("_get_node").data("parent");
                if (parent != gDisplayedReadableItem)
                {
                	$('#searchResultsMenu').jstree("deselect_all");
                }                    
            });              
    	}
    });    
});  
   
// Needed for IE only to avoid the tree from infinitely loading
if (navigator.appName.indexOf('Microsoft') != -1)
{
    $.vakata.xslt = function (xml, xsl, callback) 
    {
        var rs = "", xm, xs, processor, support;
        if(window.ActiveXObject) 
        {      
            var xslt = new ActiveXObject("Msxml2.XSLTemplate");
            var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
            var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
            xmlDoc.loadXML(xml);
            xslDoc.loadXML(xsl);
            xslt.stylesheet = xslDoc;
            var xslProc = xslt.createProcessor();
            xslProc.input = xmlDoc;
            xslProc.transform();
            callback.call(null, xslProc.output);
            
            return true;
        }     
    }
}    

function getCheckedItems()
{
    $('#menu').jstree("get_checked", null, true).each(function () 
    {
        alert(this.id + " - " + this.location + " - " + $(this).jstree("_get_node").attr("location"));
    });    	
}

function getSelectedItem()
{
    $('#menu').jstree("get_selected").each(function () 
    {
        alert("Selected >" + this.id + "<");
    });     
}

function showContentsSimplePost(aLocation) 
{
    jQuery(function() 
    {
        jQuery.post("/ocean/showcontents.ocean",
        {  
            location:  aLocation,
        },
        function(data)
        {
           jQuery("#contents").replaceWith('<div id="contents">' + data + '</div>');
        });
    });
}  

function populateContents(aData)
{
    jQuery("#contents").html(aData);
    
	// Set the height of the body section to be the height of the window
    jQuery("#contents").height(gHeightOfMiddleSection).css({overflow:"auto", width:"100%"});	    	    	
}

function displayContentsSection(aSectionId, aArrayOfTextToHighlight)
{
    // If a section id is specified then move to
    // that location, otherwise scroll to the top
    if ((aSectionId != null) && (aSectionId != "undefined"))
    {
        var sectionIdSelector = "#" + aSectionId;
        window.location.href = sectionIdSelector;
        
        jQuery(sectionIdSelector).css({backgroundColor: 'yellow'})
        
        if (aArrayOfTextToHighlight != null)
        {
            var textContentsToHighlight = jQuery(sectionIdSelector).html();
            for (var i = 0; i < aArrayOfTextToHighlight.length; i++)
            {
                var regex = new RegExp(aArrayOfTextToHighlight[i], "g");
                var textWithHighlight = "<b><u>" + aArrayOfTextToHighlight[i] + "</u></b>";
                textContentsToHighlight = textContentsToHighlight.replace(regex, textWithHighlight);    
            }
            jQuery(sectionIdSelector).html(textContentsToHighlight);
        }
    }
    else
    {
        // Make sure we are back at the top
        jQuery("#contents").scrollTop(0);
    }	 
    
    // hide the loading image
    hideLoading();  
}

function showContents(aNodeId, aSectionId, aArrayOfTextToHighlight) 
{                            
	showLoading();
	
	// If the displayed readable item is the same as the readable
	// item that should be displayed then save a server trip and
	// just do it.
	if (gDisplayedReadableItem == aNodeId)
	{
		displayContentsSection(aSectionId, aArrayOfTextToHighlight);
	}
	else
	{
    	gDisplayedReadableItem = aNodeId;        	        	

    	var errorMessage = "Sorry about this, but I could not find the contents you requested";
    	var dataToPass = "nodeId=" + aNodeId;
    	
    	if ((aNodeId != null) && (aNodeId != "undefined"))
    	{
            jQuery(function() 
            {       
            	jQuery.ajax(
                {
            		  url: "/ocean/showcontents.ocean",
            		  //type: "POST",
            		  cache: false,
            		  data: dataToPass,
            		  success: function(data)
            		  {
            			  populateContents(data);
            			  
            			  displayContentsSection(aSectionId, aArrayOfTextToHighlight);
            			  
            	          // hide the loading image
            	          hideLoading();  
            		  },
                      error: function (XMLHttpRequest, textStatus, errorThrown) 
                      {
                    	  populateContents(errorMessage);
                    	  
                          // hide the loading image
                          hideLoading();  	                    	  
                      }
            	})
            });
    	}
    	else
    	{
    		populateContents(errorMessage);
    	}
	}
}    

function displaySearchResults(aSearchResults) 
{       
    $("#searchResultsMenu").jstree({         
        "json_data" : 
        {
        	"data" : aSearchResults
        },
        "ui" : 
        {
            "select_limit" : 1
        },    
        "themeroller" :
        {
        	"item" : "ocean-state-item"
        },
        "plugins" : [ "json_data", "ui", "themeroller" ]
    }); 
    
    // When a node is selected
    $("#searchResultsMenu").bind("select_node.jstree", function(event, data)
    {               	
    	var id = data.rslt.obj.data("id");
    	var content = data.rslt.obj.data("content");
    	var parent = data.rslt.obj.data("parent");
    	
    	var textToHighlight = new Array();
    	 
    	var highlightIndex = 0;
    	jQuery(content).contents().each(function()
    	{
    	    textToHighlight[highlightIndex] = $(this).text();            	    
    	    highlightIndex++;
    	});
    	
    	if ((content == null) || (content == "undefined") || (content == "null"))
    	{
    		data.inst.toggle_node(data.rslt.obj);
    	}
    	else
    	{
            //jQuery("#contents").html(content); 
    		showContents(parent, id, textToHighlight);
    	}
    });              
}

function getItemsToSearch()
{
	var itemsToSearch = "";
	
    $('#menu').jstree("get_checked", null, true).each(function () 
    {
    	// If an item has already been added to the
    	// items to search then seperate them with 
    	// an OR
    	if (itemsToSearch != "")
    	{
    		itemsToSearch += " OR ";
    	}	
    	
    	itemsToSearch += this.id;
    });    
    
    return itemsToSearch;
}

function searchByText() 
{          
	var searchTextField = document.getElementById('searchInput');
	var searchText = jQuery.trim(searchTextField.value);
	
	if (searchText.length < 2)
	{
		jQuery("#alertDialog").html(alertIcon + "Search text must contain at least two characters.").css({'color': 'red'});
		customAlert(searchTextField);
		return false;
	}
	
	showLoading();	
	
	// Clear out the search results text
	jQuery("#searchResultsMenu").html("");
	
	var searchItems = getItemsToSearch();
    var dataToPass = "searchText=" + searchText + "&searchItems=" + searchItems;
    // alert("dataToPass >" + dataToPass + "<")
    
    if ((searchText != null) && (searchText != "undefined"))
    {
        jQuery(function() 
        {       
            jQuery.ajax(
            {
                  url: "/ocean/searchByText.ocean",
                  //dataType: "json",
                  //type: "POST",
                  cache: false,
                  data: dataToPass,
                  success: function(aData)
                  {
                	  trimmedData = jQuery.trim(aData);
                	  if ((trimmedData != null) && (trimmedData != "[]") && (trimmedData != ""))
                	  {
	                	  //alert("aData >" + aData + "<");
	                	  displaySearchResults(jQuery.parseJSON(trimmedData));
	                	  
	                	  /*var searchResults = aData; 
	
	                	  for (jsonObjectItem in searchResults)
	                	  {
	                	      if (searchResults.hasOwnProperty(jsonObjectItem))
	                	      {
	                	    	  var item = searchResults[jsonObjectItem];
	                	          var numOfItems = item.length;
	                	    	 
	                	    	  for (i = 0; i < numOfItems; i++)
	                	          {
	                	    		  alert("id >" + item[i].id + "< content >" + item[i].content);
	                	          }                        	    	 
	                	      }
	                	  } */  
                	  }
                	  else
                      {
                		  jQuery("#searchResultsMenu").html("No search results found. <p/> " 
                				                            + "This could be because the text you searched for " 
                				                            + "could not be found in any document. <p/>" 
                				                            + "Or your search only contained very common words " 
                				                            + "(e.g. you should avoid only searching for words " 
                				                            + "like and, if, be, or, from, this etc.)").css({'color': 'red'});                		  
                	  }
                	  
                	  // Open search results section
                	  $("#menuAccordion").accordion("activate", 1);
                	  
                      // hide the loading image
                      hideLoading();                          	  
                  },
                  error: function (XMLHttpRequest, textStatus, errorThrown) 
                  {
	              	  jQuery("#alertDialog").html(alertIcon 
	              			                      + "Unfortunately an error occurred.  <p/>" 
	              			                      + "Status: " + textStatus
	              			                      + "<br/> Error: " + errorThrown).css({'color': 'red'});
	            	  customAlert(searchTextField);                    	                        
                      
                      // hide the loading image
                      hideLoading();                                
                  }
            })
        });
    }
    else
    {
		jQuery("#alertDialog").html(alertIcon + "No search text was entered.").css({'color': 'red'});
		customAlert(searchTextField);    	
    }
} 

function customAlert(aFieldToFocus) 
{	
	jQuery("#alertDialog").dialog(
	{
		resizable: false,
		height:200,
		width:400,
		modal: true,
		buttons: 
		{
			"OK": function() 
			{
				jQuery(this).dialog("close");
				
				if ((aFieldToFocus != null) && (aFieldToFocus != "undefined"))
				{
					aFieldToFocus.focus();
				}
			}
		}
	});
}

function handleKeyPress(aEvent, aFunction)
{
	var key = aEvent.keyCode || aEvent.which;
	
	// Enter key
	if (key == 13)
	{
		aFunction();
	}
}